﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using MediatR;
using Microsoft.Extensions.Logging;
using Traceability.Register.Application.Commonds.TraceabilityManagementCommonds;
using Traceability.Register.Domain;
using Traceability.Register.ErrorCode.Result;
using Traceability.Register.Infrastructrue;

namespace Traceability.Register.Application.CommondHandlers.TraceabilityManagementCommondHandlers
{
    /// <summary>
    /// 养殖场添加请求命令处理
    /// </summary>
    public class InsertBreedingsCommondHandler : IRequestHandler<InsertBreedingsCommond, ApiResult>
    {
        /// <summary>
        /// AutoMapper
        /// </summary>
        private readonly IMapper mapper;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<InsertBreedingsCommondHandler> logger;
        /// <summary>
        /// 养殖场仓储
        /// </summary>
        private readonly IBaseRepository<Breedings> baseRepository;
        /// <summary>
        /// 构造函数依赖注入
        /// </summary>
        /// <param name="mapper">AutoMapper</param>
        /// <param name="logger">日志</param>
        /// <param name="baseRepository">养殖场仓储</param>
        public InsertBreedingsCommondHandler(IMapper mapper, ILogger<InsertBreedingsCommondHandler> logger, IBaseRepository<Breedings> baseRepository)
        {
            this.mapper = mapper;
            this.logger = logger;
            this.baseRepository = baseRepository;
        }

        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回结果</returns>
        public async Task<ApiResult> Handle(InsertBreedingsCommond request, CancellationToken cancellationToken)
        {
            try
            {
                var entity = mapper.Map<Breedings>(request);
                await baseRepository.InsertAsync(entity);
                return ApiResult.Ok();
            }
            catch (Exception ex)
            {
                logger.LogError("添加失败" + ex.Message);
                throw;
            }
        }
    }
}
